<template>
  <div>
    <el-image
      class="cursor-pointer border border-dashed border-2px border-gray-300"
      :style="{ width: `${props.width}px`, height: `${props.height}px` }"
      fit="scale-down"
      :src="image"
      @click="open"
    >
      <template #error>
        <div class="text-12px w-1/1 h-1/1 flex-col flex justify-center" @click="open">
          <Plus class="m-auto" :style="{ width: `30%`, height: `30%` }" color="#d7d7d7" />
        </div>
      </template>
    </el-image>
    <SuCaiPopup ref="sucaiRef" :fileType="props.fileType" @confirm="getUrl" :maxSelect="1"></SuCaiPopup>
  </div>
</template>

<script setup lang="ts">
import SuCaiPopup from "@/components/UploadCool/index.vue";
import { ref, watch } from "vue";
import { useUserStore } from "@/stores/modules/user";
import { url } from "@/utils/index";

const {
  userInfo: { prefix }
} = useUserStore();

// 当前展示的图片
const image = ref("");
const emits = defineEmits(["update:url", "get-cover"]);

interface Props {
  width?: number;
  height?: number;
  fileType?: string;
  cover?: string;
  url: string;
}

const props = withDefaults(defineProps<Props>(), {
  width: 100,
  height: 100,
  fileType: "image",
  cover: ""
});

const sucaiRef = ref<InstanceType<typeof SuCaiPopup> | null>();

// 打开素材库
const open = () => {
  sucaiRef.value?.change();
};
// 获取图片
const getUrl = (val: any) => {
  if (props.fileType === "image") {
    image.value = val[0].origin_name;
    console.log("");
  } else if (props.fileType === "video") {
    setTimeout(() => {
      image.value = val[0].cover;
      emits("get-cover", image.value);
    });
  }
  emits("update:url", "/" + val[0].base_url);
};

// 初始化图片
watch(
  () => props.url,
  () => {
    if (props.fileType === "image") {
      if (!props.url.includes(prefix)) {
        image.value = url(prefix, props.url);
      } else {
        image.value = props.url;
      }
    } else if (props.fileType === "video") {
      image.value = props.cover;
    }
  },
  { immediate: true }
);
</script>

<style></style>
